// 预处理中间件
package middleware

import (
	"context"
	"device-admin/config/redis"
	"device-admin/internal/define"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

// ParamsHandle 参数预处理
func ParamsHandle() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		if token == "" {
			token = c.Query("Authorization")
		}
		rdb := redis.NewDB()
		// 获取会话参数
		timeoutCtx, cancel := context.WithTimeout(context.Background(), time.Second*3)
		defer cancel()
		valueMap, _ := rdb.HGetAll(timeoutCtx, define.UserLoginTokenPrefix+token).Result()
		c.Set("authorization", token)
		c.Set("user_id", valueMap["user_id"])
		c.Set("username", valueMap["username"])
		c.Set("merchant_id", valueMap["merchant_id"])
		c.Set("merchant_name", valueMap["merchant_name"])
		c.Set("role_id", valueMap["role_id"])
		c.Set("merchant_path", valueMap["merchant_path"])
		c.Set("user_merchant_path", strings.Join([]string{valueMap["merchant_path"], valueMap["merchant_id"]}, ">"))
		// …… 获取其他参数
		c.Next()
	}
}
